package org.jeecg.modules.demo;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;

import java.io.File;
import java.io.FileReader;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.UUID;

/**
 * 微信支付工具类
 */
public class WechatPayUtil {

    // 静态代码块注册BouncyCastle提供者
    static {
        // 检查是否已注册，避免重复注册
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    /**
     * 加载商户私钥
     */
    public static PrivateKey loadPrivateKey(File privateKeyFile) throws Exception {
        try (PemReader pemReader = new PemReader(new FileReader(privateKeyFile))) {
            PemObject pemObject = pemReader.readPemObject();
            byte[] content = pemObject.getContent();

            // 使用PKCS8格式解析私钥
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(content);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
            return keyFactory.generatePrivate(keySpec);
        }
    }

    /**
     * 生成签名
     */
    public static String generateSignature(String message, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance("SHA256withRSA", BouncyCastleProvider.PROVIDER_NAME);
        signature.initSign(privateKey);
        signature.update(message.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(signature.sign());
    }

    /**
     * 生成随机字符串
     */
    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    /**
     * 获取当前时间戳
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis() / 1000;
    }
}
